package de.hhbk.feedbackmodul.daobeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import de.hhbk.feedbackmodul.daointerfaces.SurveyDaoIF;
import de.hhbk.feedbackmodul.entities.Survey;

@Stateless
public class SurveyDaoBean implements SurveyDaoIF {

	@PersistenceContext(unitName = "FeedbackModulEJB")
	private EntityManager manager;
	
	private Logger logger = Logger.getLogger(this.getClass());

	@SuppressWarnings("unchecked")
	@Override
	public List<Survey> getAllSurveys() throws Exception {
		try
		{
			Query query = manager.createQuery("select s from Survey s", Survey.class);
			return (List<Survey>)query.getResultList();
		}
		catch(Exception e)
		{
			logger.error("Error while reading Surveys: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void createSurvey(Survey umfrage) throws Exception {
		try
		{
			manager.persist(umfrage);
		}
		catch(Exception e)
		{
			logger.error("Error while persisting Survey: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void updateSurvey(Survey umfrage) throws Exception {
		try
		{
			manager.merge(umfrage);
		}
		catch(Exception e)
		{
			logger.error("Error while updating Survey: "+e.getMessage(), e);
			throw e;
		}
	}


	@Override
	public void deleteSurvey(Survey umfrage) throws Exception {
		try
		{
			Survey surveyToDelete = manager.find(Survey.class, umfrage.getId());
			manager.remove(surveyToDelete);
		}
		catch(Exception e)
		{
			logger.error("Error while deleting Survey: "+e.getMessage(), e);
			throw e;
		}
		
	}


}
